package elastic.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import elastic.log.SearchLog;
import elastic.service.SearchService;
import elastic.util.SearchFileUtil;
import org.json.JSONException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author quxb
 * @version 1.0
 * @project 深圳OA
 * @package zhbg.oaxt.elastic
 * @file SearchVo.java 创建时间:2018年7月23日下午3:51:07
 * @title 标题（要求能简洁地表达出类的功能和职责）
 * @description 描述（简要描述类的职责、实现方式、使用注意事项等）
 * @copyright Copyright (c) 2018 中国软件与技术服务股份有限公司
 * @company 中国软件与技术服务股份有限公司
 * @module 模块: 模块名称
 * @reviewer 审核人
 * @history 修订历史（历次修订内容、修订人、修订时间等）
 */
@RestController
@RequestMapping("/search")
public class SearchCtrl {

    /**
     * service 注入
     */
    @Autowired
    SearchService searchService;

    /**
     * 请求重试次数
     * 仅用于增删改，查询不重试
     */
    public static final int HTTP_SYNC_RETRY_TIMES = 0;
    Logger logger= LoggerFactory.getLogger(SearchCtrl.class);

    static{
    	SearchService.init();
    	SearchLog.init();
    }
    /**
     * 添加或更新索引
     *
     * @param index 索引名称
     * @param id    主键
     * @param value 待存储内容
     * @return json串
     */
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST, produces = {"text/html; charset=UTF-8"})
    public String saveOrUpdateSearch(HttpServletRequest request,@RequestParam(value = "index", required = true) String index,
                                         @RequestParam(value = "id", required = true) String id,
                                         @RequestParam(value = "value", required = true) String value) throws UnsupportedEncodingException {
        logger.info("ESLOG saveOrUpdate: "+"\nsessionId-- "+request.getParameter("sessionId")+"\nindex-- "+index+"\nid-- "+id+"\nvalue-- "+value);
        request.setCharacterEncoding("UTF-8");
        SearchLog.postLog("saveOrUpdate", index, id, value, null, HTTP_SYNC_RETRY_TIMES, "soa", "receive", false,request.getParameter("sessionId"));
        return searchService.saveOrUpdateSearch(index, id, value, false,request.getParameter("sessionId"),HTTP_SYNC_RETRY_TIMES);
    }

    /**
     * 全文检索库添加或修改
     *
     * @param index 索引名称
     * @param id    主键
     * @param value 待存储内容
     * @return json串
     */
    @RequestMapping(value = "fullTextSaveOrUpdate", method = RequestMethod.POST, produces = {"text/html; charset=UTF-8"})
    public String fullTextSaveOrUpdateSearch(HttpServletRequest request,@RequestParam(value = "index", required = true) String index,
                                         @RequestParam(value = "id", required = true) String id,
                                         @RequestParam(value = "value", required = true) String value) throws UnsupportedEncodingException {
        logger.info("ESLOG fullTextSaveOrUpdate: "+"\nsessionId-- "+request.getParameter("sessionId")+"\nindex-- "+index+"\nid-- "+id+"\nvalue-- "+value);
        request.setCharacterEncoding("UTF-8");
        SearchLog.postLog("fullTextSaveOrUpdate", index, id, value, null, HTTP_SYNC_RETRY_TIMES, "soa", "receive", false,request.getParameter("sessionId"));
        return searchService.saveOrUpdateSearch(index, id, value, true,request.getParameter("sessionId"),HTTP_SYNC_RETRY_TIMES);
    }

    /**
     * 添加到es
     *
     * @param index index
     * @param id    id
     * @param value value
     * @return 是否成功
     */
    @RequestMapping(value = "add", method = RequestMethod.POST, produces = {"text/html; charset=UTF-8"})
    public String addSearch(HttpServletRequest request,@RequestParam(value = "index", required = true) String index,
                                @RequestParam(value = "id", required = true) String id,
                                @RequestParam(value = "value", required = true) String value) throws UnsupportedEncodingException {
        logger.info("ESLOG add: "+"\nsessionId-- "+request.getParameter("sessionId")+"\nindex-- "+index+"\nid-- "+id+"\nvalue-- "+value);
        request.setCharacterEncoding("UTF-8");
        SearchLog.postLog("add", index, id, value, null, HTTP_SYNC_RETRY_TIMES, "soa", "receive", false,request.getParameter("sessionId"));
        return searchService.addSearch(index, id, value, false,request.getParameter("sessionId"),HTTP_SYNC_RETRY_TIMES);
    }
    
    /**
     * 全文检索添加到es
     *
     * @param index 索引名称
     * @param id    主键
     * @param value 待存储内容
     * @return json串
     */
    @RequestMapping(value = "fullTextAdd", method = RequestMethod.POST, produces = {"text/html; charset=UTF-8"})
    public String fullTextAddSearch(HttpServletRequest request,@RequestParam(value = "index", required = true) String index,
                                @RequestParam(value = "id", required = true) String id,
                                @RequestParam(value = "value", required = true) String value) throws UnsupportedEncodingException {
        logger.info("ESLOG fullTextAdd: "+"\nsessionId-- "+request.getParameter("sessionId")+"\nindex-- "+index+"\nid-- "+id+"\nvalue-- "+value);
        request.setCharacterEncoding("UTF-8");
        SearchLog.postLog("fullTextAdd", index, id, value, null, HTTP_SYNC_RETRY_TIMES, "soa", "receive", false,request.getParameter("sessionId"));
        return searchService.addSearch(index, id, value, true,request.getParameter("sessionId"),HTTP_SYNC_RETRY_TIMES);
    }

    /**
     * 修改es数据
     *
     * @param index 索引名称
     * @param id    主键
     * @param value 待存储内容
     * @return json串
     */
    @RequestMapping(value = "update", method = RequestMethod.POST, produces = {"text/html; charset=UTF-8"})
    public String updateSearch(HttpServletRequest request,@RequestParam(value = "index", required = true) String index,
                                   @RequestParam(value = "id", required = true) String id,
                                   @RequestParam(value = "value", required = true) String value) throws UnsupportedEncodingException {
        logger.info("ESLOG update: "+"\nsessionId-- "+request.getParameter("sessionId")+"\nindex-- "+index+"\nid-- "+id+"\nvalue-- "+value);
        request.setCharacterEncoding("UTF-8");
        SearchLog.postLog("update", index, id, value, null, HTTP_SYNC_RETRY_TIMES, "soa", "receive", false,request.getParameter("sessionId"));
        return searchService.updateSearch(index, id, value, false,request.getParameter("sessionId"),HTTP_SYNC_RETRY_TIMES);
    }
    
    /**
     * 全文索引库修改es数据
     *
     * @param index 索引名称
     * @param id    主键
     * @param value 待存储内容
     * @return json串
     */
    @RequestMapping(value = "fullTextUpdate", method = RequestMethod.POST, produces = {"text/html; charset=UTF-8"})
    public String fullTextUpdateSearch(HttpServletRequest request,@RequestParam(value = "index", required = true) String index,
                                   @RequestParam(value = "id", required = true) String id,
                                   @RequestParam(value = "value", required = true) String value) throws UnsupportedEncodingException {
        logger.info("ESLOG fullTextUpdate: "+"\nsessionId-- "+request.getParameter("sessionId")+"\nindex-- "+index+"\nid-- "+id+"\nvalue-- "+value);
        request.setCharacterEncoding("UTF-8");
        SearchLog.postLog("fullTextUpdate", index, id, value, null, HTTP_SYNC_RETRY_TIMES, "soa", "receive", false,request.getParameter("sessionId"));
        return searchService.updateSearch(index, id, value, true,request.getParameter("sessionId"),HTTP_SYNC_RETRY_TIMES);
    }

    /**
     * 删除es数据
     *
     * @param index 索引名称
     * @param id    主键
     * @return json串
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST, produces = {"text/html; charset=UTF-8"})
    public String deleteSearch(HttpServletRequest request,@RequestParam(value = "index", required = true) String index,
                                   @RequestParam(value = "id", required = true) String id) throws UnsupportedEncodingException {
        logger.info("ESLOG delete: "+"\nsessionId-- "+request.getParameter("sessionId")+"\nindex-- "+index+"\nid-- "+id);
        request.setCharacterEncoding("UTF-8");
        SearchLog.postLog("delete", index, id, null, null, HTTP_SYNC_RETRY_TIMES, "soa", "receive", false,request.getParameter("sessionId"));
        return searchService.deleteSearch(index, id,request.getParameter("sessionId"),HTTP_SYNC_RETRY_TIMES);
    }

    /**
     * 检索
     *
     * @param index      索引名称
     * @param query      检索条件
     * @param fields     返回字段
     * @param orderField 排序字段，传入格式为 字段名#排序方向， 例如：field#desc
     * @param from       分页/起始 从1开始计数
     * @param size       分页/条数
     * @param highLights 高亮字段
     * @param preTag     高亮标签前缀
     * @param postTag    高亮标签后缀
     * @return 检索结果，json串表示
     */
    @RequestMapping(value = "search", method = {RequestMethod.POST, RequestMethod.GET}, produces = {"text/html; charset=UTF-8"})
    public String search(HttpServletRequest request,@RequestParam(value = "index", required = true) String index,
                         @RequestParam(value = "query", required = false) String query,
                         @RequestParam(value = "fields", required = false) String fields,
                         @RequestParam(value = "orderFieldList", required = false) List<String> orderFieldList,
                         @RequestParam(value = "from", required = true) int from,
                         @RequestParam(value = "size", required = true) int size,
                         @RequestParam(value = "highLights", required = false) String highLights,
                         @RequestParam(value = "preTag", required = false) String preTag,
                         @RequestParam(value = "postTag", required = false) String postTag) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        return searchService.search(index, query, fields, orderFieldList, from, size, highLights, preTag, postTag);
    }

    /**
     * 检索--督查
     *
     * @param index     索引名称
     * @param query     检索条件
     * @param aggregate_word 用户身份
     * @return 检索统计结果
     */
    @RequestMapping(value = "aggregate", method = {RequestMethod.POST, RequestMethod.GET}, produces = {"text/html; charset=UTF-8"})
    public String aggregate(HttpServletRequest request,@RequestParam(value = "index", required = true) String index,
                                @RequestParam(value = "query", required = false) String query,
                                @RequestParam(value = "aggregate_word", required = true) String aggregate_word) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        return searchService.aggregate(index, query, aggregate_word);
    }

    /**
     * 留作测试
     * @return string
     * @throws JSONException
     * @throws IPException
     */
    @RequestMapping(value = "move", method = {RequestMethod.POST, RequestMethod.GET})
    public String move() throws JSONException {
        return searchService.move();
    }

}
